#include"log.hpp"
#include"process.hpp"  
using namespace std;
extern LOG log;

int main()
{
    Pipe pipe;
    int fd=0;
    pipe.open_pipes(fd);
    int shmid = CreateMemory();
    log(DEBUG, "CreateMemory success, shmid: %d", shmid);

    char* shmaddr=(char*)shmat(shmid, nullptr, 0);
    if(shmaddr == (char*)-1)
    {
        log(FATAL, "shmat failed: %s", strerror(errno));
        exit(3);
    }
    
    shmid_ds shm_info;
    int shmctl_ret1= shmctl(shmid, IPC_STAT, &shm_info);
    while(1)
    {
        char tmp=0;
        int n = read(fd, &tmp, 1);
        if(n < 0)
        {
            log(FATAL, "read failed: %s", strerror(errno));
            exit(6);
        }
        else if(n == 0)
        {
            log(INFO, "read end of pipe");
            break; // 读端关闭，退出循环
        }
        char arr[SIZE]={0};
        cout<<"this is server:"<<shmaddr<<endl;
        // cout<<shm_info.shm_nattch<<" clients attached"<<endl;
        // cout<<shm_info.shm_segsz<<" bytes in segment"<<endl;
        sleep(1);
    }
    int ret=shmdt(shmaddr);
    if(ret == -1)
    {
        log(FATAL, "shmdt failed: %s", strerror(errno));
        exit(4);
    }
    log(DEBUG, "shmdt success, shmaddr: %p", shmaddr);

    
    int shmctl_ret2 = shmctl(shmid, IPC_RMID, nullptr);
    if(shmctl_ret2 == -1)
    {
        log(FATAL, "shmctl failed: %s", strerror(errno));
        exit(5);
    }
    log(INFO, "shmctl success, shared memory removed");
    return 0;
}